<?php

namespace lib\upload;
/***
 * 
 */
class UploadFile{
	
	public $uploadFile;
	public $ext;//扩展名
	public $size;

	public function __construct($uploadFile, $maxSize = 0, $allowableExt = []){

		$this->uploadFile = $uploadFile;

		if(!isset($uploadFile["error"]) || intval($uploadFile["error"]) != 0){
			throw new \RuntimeException("上传文件错误", -1);
		}

		$this->size = $uploadFile["size"];
		if($maxSize > 0 && $this->size > $maxSize){
			$tempMsg = "文件大小".number_format($this->size/1024,2)."K,超过要求的最大值".number_format($maxSize/1024,2)."K";
			throw new \RuntimeException($tempMsg, -2);
		}

		$this->ext = self::getExtName($uploadFile["name"]);
		if(is_array($allowableExt) && count($allowableExt)>0){

			foreach($allowableExt as &$value){
				$value = strtolower($value);
				$value = str_replace(".", "", $value);
			}

			if(!in_array($this->ext, $allowableExt)){
				throw new \RuntimeException("上传文件类型错误", -3);
			}

		}

	}

	/**
	 * ????????????????????????
	 */
	public function mv($filepath, $filename = ''){
		$filepath = str_replace("\\", "/", trim($filepath));
		$filepath = str_replace("//", "/", $filepath);
		$filepath = trim($filepath, "/");//去掉两边边的斜杠

		$filename = ($filename == "") ? $this->uploadFile["name"] : $filename;

		if(!file_exists($filepath) || !is_writable($filepath)){
			return false;
		}

		$filesrc = $filepath."/".$filename;

		return move_uploaded_file($this->uploadFile["tmp_name"], $filesrc);
	}

	public function mvRandName($filepath, $len){
		$filename = self::randstr($len).".".$this->ext;
		return $this->mv($filepath, $filename);
	}

	/**
	 * 得到文件的扩展名
	 * @param $filename
	 * @return string
	 */
	public static function getExtName($filename){
		$ext = strtolower(strrchr($filename, "."));
		$ext = str_replace(".", "", $ext);
		return $ext;
	}

	/**
	 * ????????????????????
	 * @author YUE
	 * @date 20160906
	 */
	public static function randstr($len){
		$pattern = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$randstr = "";
		for($i = 0; $i< $len; $i++) { 
			$randstr .= $pattern[mt_rand(0,35)];
		}
		return $randstr;
	}
	
	/**
	 * ????????????????????????(????????????)
	 * ???? ???? d:\abc\  ?????????? d:/abc/20160906
	 * @author YUE
	 * @date 20160906
	 */
	public static function createDateFolder($dir){
		$dir = rtrim(str_replace("//", "/", str_replace("\\", "/", trim($dir))), "/");//???????????????????????????б??
		if(!file_exists($dir))return -1;
		$datefolder = date("Ymd", time());
		$newdir = $dir."/".$datefolder;
		if(!file_exists($newdir)){
			if(!mkdir($newdir)){
				return -2;	
			}
		}
		return $datefolder;
	}

}
?>